import os.path
import shutil
import subprocess
import datetime
import os

from pbxproj import XcodeProject
from pbxproj.pbxextensions import ProjectFiles, FileOptions, TreeType, HeaderScope

pod_data = '''
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'Unity-iPhone' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for Unity-iPhone

  target 'Unity-iPhone Tests' do
    inherit! :search_paths
    # Pods for testing
  end
  pod 'MyLayout'
end

target 'UnityFramework' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for UnityFramework

end
'''

opt_data = '''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>destination</key>
	<string>export</string>
	<key>manageAppVersionAndBuildNumber</key>
	<false/>
	<key>method</key>
	<string>app-store-connect</string>
	<key>provisioningProfiles</key>
	<dict>
		<key>com.battleborn.iosen</key>
		<string>sgbxdUSA</string>
	</dict>
	<key>signingCertificate</key>
	<string>8DD759FB1D9D83F02D11403D561054736B1A5C7E</string>
	<key>signingStyle</key>
	<string>manual</string>
	<key>stripSwiftSymbols</key>
	<true/>
	<key>teamID</key>
	<string>D6BMXWL7WC</string>
	<key>uploadSymbols</key>
	<true/>
</dict>
</plist>
'''


def write_pod():
    pod_file_name = 'Podfile'
    if os.path.exists(pod_file_name):
        print("Pod 文件已存在 无需创建")
    else:
        pod_file = open(pod_file_name, 'w')
        pod_file.write(pod_data)
        pod_file.close()


def write_opt():
    opt_name = 'po.plist'
    if os.path.exists(opt_name):
        print('opt file exit')
    else:
        opt_file = open(opt_name, 'w')
        opt_file.write(opt_data)
        opt_file.close()


def pod_install():
    os.chdir('App')
    ret = subprocess.run('pod install', shell=True)
    return ret


def connect_google():
    ret = subprocess.run("ping -c1 www.google.com", shell=True)
    if ret.returncode == 0:
        return True
    elif ret.returncode == 2:
        print('无法连接Pod仓库，请连接VPN后 重试')
        return False


def out_obj():
    now = datetime.datetime.now()
    now_time_str = now.strftime('%y%m%d%H%M')
    # tar = '/Users/pub/jenkins/workspace/{0}'.format(now_time_str)
    tar = ''.format(now_time_str)
    xcode = '''
    xcodebuild archive -workspace Unity-iPhone.xcworkspace -scheme Unity-iPhone -configuration Release -archivePath {0}.xcarchive
    xcodebuild -exportArchive -archivePath {0}.xcarchive -configuration Release -exportPath IPA{1} -exportOptionsPlist po.plist
    '''
    #
    # xcodebuild archive - workspace ${project_path} /${project_name}.xcworkspace
    xcode = xcode.format(now_time_str, now_time_str)
    print(xcode)
    return subprocess.run(xcode, shell=True)


def build_process():
    can_connect = connect_google()
    if can_connect:
        write_pod()
        write_opt()
        ret = pod_install()
        if ret.returncode == 0:
            print("Pod 执行完成")
            out_obj()
            # ret =
            # if ret.returncode == 0:
            #     print("Build ipa success")
            # else:
            #     print("Build ipa fail")


#
#

def git_clone():
    clone_git = '''
        cd ../
        git clone git@gitee.com:KaiXinDragon/unity-game-frame-work.git
        '''
    print(clone_git)
    return subprocess.run(clone_git, shell=True)


def git_pull():
    clone_git = '''
        git reset --hard HEAD
        git pull
        '''
    print(clone_git)
    return subprocess.run(clone_git, shell=True)


def git_update():
    current_directory = os.getcwd()
    parent_directory = os.path.dirname(current_directory)
    print(current_directory)
    if os.path.exists(parent_directory + '/unity-game-frame-work'):
        os.chdir(parent_directory + '/unity-game-frame-work')
        print(os.getcwd())
        git_pull()

    else:
        git_clone()


def copy_podfile():
    current_directory = os.getcwd()
    parent_directory = os.path.dirname(current_directory)

    target_path = current_directory + "/App/Podfile"

    res_parent = os.path.dirname(current_directory)

    res_path = res_parent + "/unity-game-frame-work/Podfile"

    if os.path.exists(target_path):
        os.remove(target_path)

    shutil.copy(res_path, target_path)


pb_file_path = 'App/Unity-iPhone.xcodeproj/project.pbxproj'
unity_iphone = "Unity-iPhone"
unity_framework = "UnityFramework"

x_project = XcodeProject.load(pb_file_path)


def get_root():
    root_group = x_project.get_or_create_group("LXB")
    cur_dir = os.getcwd()
    target_dir = cur_dir + "/App/LXB"
    folders = os.listdir(target_dir)
    insert_frame(root_group, folders, target_dir)

    frameworks = x_project.get_or_create_group("Frameworks")
    file_options = FileOptions(weak=True, embed_framework=False)
    x_project.add_file('System/Library/Frameworks/AdSupport.framework', parent=frameworks, target_name=unity_iphone, tree='SDKROOT', force=False,
                     file_options=file_options)

    file_options = FileOptions(weak=True, embed_framework=False)
    x_project.add_file('System/Library/Frameworks/StoreKit.framework', parent=frameworks, target_name=unity_framework,
                       tree='SDKROOT', force=False,
                       file_options=file_options)

    file_options = FileOptions(weak=True, embed_framework=False)
    x_project.add_file('System/Library/Frameworks/libate.tbd', parent=frameworks, target_name=unity_iphone,
                       tree='SDKROOT', force=False,
                       file_options=file_options)

def insert_frame(group, folders, parent_path):
    for sub_folder in folders:
        is_bundle = sub_folder.endswith('bundle')
        if os.path.isdir(parent_path + '/' + sub_folder) and is_bundle == False:
            sub_group = x_project.get_or_create_group(sub_folder, parent=group)
            s_folders = os.listdir(parent_path + "/" + sub_folder)
            insert_frame(sub_group, s_folders, parent_path + "/" + sub_folder)
        else:
            if sub_folder.endswith('mm') | sub_folder.endswith('h'):
                x_project.add_file(os.path.abspath(parent_path + "/" + sub_folder), parent=group, tree=TreeType.GROUP,
                                   target_name=unity_framework, force=False)
            elif sub_folder.endswith('.a'):
                x_project.add_file(os.path.abspath(parent_path + "/" + sub_folder), parent=group, tree=TreeType.GROUP,
                                   target_name=unity_framework, force=False)
            elif sub_folder.endswith('.plist'):
                x_project.add_file(os.path.abspath(parent_path + "/" + sub_folder), target_name=unity_iphone,
                                   parent=group, force=False)
            elif sub_folder.endswith('.bundle'):
                x_project.add_file(os.path.abspath(parent_path + "/" + sub_folder), target_name=unity_framework,
                                   parent=group, force=False)


get_root()

x_project.save(pb_file_path)
# git_update()
# copy_podfile()
# pod_install()
print("finish")
# git_clone()
# write_pod()
# pod_install()


# build_process()
